using System;
using System.Drawing;
using System.Windows.Forms;

namespace WinApp.Services
{
    /// <summary>
    /// 多屏幕窗体移动辅助类
    /// </summary>
    public static class ScreenHelper
    {
        /// <summary>
        /// 获取鼠标所在的屏幕
        /// </summary>
        /// <param name="mousePosition">鼠标位置</param>
        /// <returns>鼠标所在的屏幕</returns>
        private static Screen GetCurrentScreen(Point mousePosition)
        {
            foreach (Screen screen in Screen.AllScreens)
            {
                if (screen.Bounds.Contains(mousePosition))
                {
                    return screen;
                }
            }
            return Screen.PrimaryScreen;
        }

        /// <summary>
        /// 确保窗体位置在有效的屏幕范围内
        /// </summary>
        /// <param name="form">要移动的窗体</param>
        /// <param name="newLocation">新的位置</param>
        /// <returns>调整后的位置</returns>
        public static Point EnsureValidPosition(Form form, Point newLocation)
        {
            // 获取所有屏幕组成的工作区
            Rectangle totalBounds = new Rectangle();
            foreach (Screen screen in Screen.AllScreens)
            {
                // 合并所有屏幕的工作区
                totalBounds = Rectangle.Union(totalBounds, screen.WorkingArea);
            }

            // 计算窗体在新位置时的边界
            int formRight = newLocation.X + form.Width;
            int formBottom = newLocation.Y + form.Height;

            // 限制左上角不能超出桌面的左上角
            newLocation.X = Math.Max(totalBounds.Left, newLocation.X);
            newLocation.Y = Math.Max(totalBounds.Top, newLocation.Y);

            // 限制左下角不能超出桌面的左下角
            if (formBottom > totalBounds.Bottom)
            {
                newLocation.Y = totalBounds.Bottom - form.Height;
            }

            // 限制右边不能超过鼠标点击的位置
            Point mousePos = Cursor.Position;
            if (formRight > mousePos.X)
            {
                newLocation.X = mousePos.X - form.Width;
            }

            return newLocation;
        }

        /// <summary>
        /// 处理窗体拖动
        /// </summary>
        /// <param name="form">要移动的窗体</param>
        /// <param name="mousePosition">当前鼠标位置</param>
        /// <param name="dragStartPosition">开始拖动时的位置</param>
        /// <param name="formStartPosition">开始拖动时窗体的位置</param>
        public static void HandleFormDrag(Form form, Point mousePosition, Point dragStartPosition, Point formStartPosition)
        {
            // 计算鼠标移动的距离
            int offsetX = mousePosition.X - dragStartPosition.X;
            int offsetY = mousePosition.Y - dragStartPosition.Y;

            // 计算窗体新的位置
            Point newLocation = new Point(
                formStartPosition.X + offsetX,
                formStartPosition.Y + offsetY
            );

            // 确保新位置在有效范围内并设置窗体位置
            form.Location = EnsureValidPosition(form, newLocation);
        }
    }
}
